package com.miraclesea.framework.dao.impl;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.beans.BeanUtils;
import org.springframework.data.jpa.domain.AbstractPersistable;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import com.miraclesea.framework.dao.BaseJpaRepository;
import com.miraclesea.framework.reflection.ReflectionUtil;

public final class BaseJpaRepositoryImpl<E extends AbstractPersistable<I>, I extends Serializable> extends SimpleJpaRepository<E, I> implements BaseJpaRepository<E, I> {

	private final EntityManager entityManager;
	
	public BaseJpaRepositoryImpl(final Class<E> domainClass, final EntityManager entityManager) {
		super(domainClass, entityManager);
		this.entityManager = entityManager;
	}
	
	@Override
	public E updateNotNull(final E entity) {
		E entityFromDb = findOne(entity.getId());
		BeanUtils.copyProperties(entity, entityFromDb, ReflectionUtil.getNullPropertyNames(entity));
		return entityManager.merge(entityFromDb);
	}
	
}
